//创建管理员相关的小仓库
import { defineStore } from "pinia";
//引入接口登录的接口
import { reqAllowEnterGroup, reqRejectEnterGroup, reqGroupEnterNext, reqPushNotice, reqGetGroupScoreList, reqStudentGetGroup, reqStudentEnterNext, reqCreateGroup, reqDisbanGroup, reqGetGroupList, reqUploadGroupFile, reqUploadFile, reqStudentUpdateInfo, reqStudentLogin, reqStudentRegister, reqStudentForgetPassword, reqStudentGetIndividualPro, reqUploadUrl, reqGetClassGroup, reqApplyEnterGroup, reqStudentGoback, reqGroupGoBack, reqCreatePro } from "@/api/student";
import type { pushNoticeParams, getGroupListrDatePrams, CreateGroupParams, getGroupsMemberDatePrams, StudentUploadDto, studentUpdate, studentLogin, studentRegister, studentForgetPassword, uploadUrlParams, applyEnterGroupsParams } from "@/api/student/type";
import { ElMessage } from 'element-plus';
import { studentRoute } from "@/router/student";
import { GET_TOKEN } from "@/utils/token";

// 预处理菜单数据，确保它是数组形式
const processMenuRoutes = () => {
    console.log('Processing student menu routes');
    console.log('Original studentRoute:', studentRoute);
    
    if (!studentRoute) {
        console.error('Student route is undefined');
        return [];
    }
    
    if (Array.isArray(studentRoute)) {
        console.log('Student route is already an array with length:', studentRoute.length);
        // 直接使用而不再创建新数组
        return studentRoute;
    } else {
        console.log('Student route is not an array, converting to array');
        return [studentRoute];
    }
};

//创建管理员小仓库               小仓库的名字 AdminStore
let useStudentStore = defineStore('StudentStore', {
    //小仓库存储数据
    state: () => {
        // 手动将菜单路由设置为studentRoute
        const menuRoutes = processMenuRoutes();
        console.log('Final student menuRoutes:', menuRoutes);
        
        return {
            token: GET_TOKEN(),
            userInfo: {
                studentUsername: '',
                studentName: '',
                studentNumber: '',
                studentEmail: '',
                studentFinish: 0,
                studentPosition: 0,
                studentNotice: '',
                giteeUrl: '',
                groupProName: '',
                groupId: -1,
                studentApplyReason: '',
                groupNotice: '',
                groupName: ''
            },
            tableData: [] as Array<{
                studentId: number;
                studentName: string;
                studentNumber: string;
                studentPosition: number;
                groupId: number;
                groupProName: string;
                studentApplyReason: string;
                studentNotice: string;
                giteeUrl: string;
                classId: number;
            }>,
            tableGroupData: [] as Array<{
                studentName: string;
                studentId: number;
                studentNumber: string;
                groupProName: string;
                groupScore: number;
                groupId: number;
                studentFinish: number; // 允许为 null
                classId: number;
                studentPosition: number;
            }>,
            tableClassGroupData: [] as Array<{
                groupId: number;
                studentId: number;
                groupName: string;
                groupProName: string;
                groupScore: number;
                groupIsAvailable: number;
                groupLeader: string;
                groupNotice: string;
                groupFinish: number;
                classId: number;
                giteeUrl: string;
            }>,
            groupInfo: {
                groupId: -1,
                studentId: -1,
                groupName: '',
                groupProName: '',
                groupScore: 0,
                groupIsAvailable: 0,
                groupLeader: '',
                groupNotice: '',
                groupFinish: 0,
                classId: -1,
                giteeUrl: ''
            },

            total: 0,
            menuRoutes, // 预处理的菜单路由
        }
    },
    //异步 逻辑的处理的地方
    actions: {
        //允许进入小组的方法
        async allowEnterGroup(data: number) {
            try {
                console.log("data:", data);
                const result = await reqAllowEnterGroup(data);
                console.log("result:", result);
                if (result.code === 200) {
                    console.log("list:", result.data);
                    ElMessage.success(result.data);
                } else {
                    ElMessage.error(`允许加入小组失败:`);
                }
            } catch (error) {

                ElMessage.error('允许加入小组失败');
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        //拒绝进入小组的方法
        async rejectEnterGroup(data: number) {
            try {
                console.log("data:", data);
                const result = await reqRejectEnterGroup(data);
                console.log("result:", result);
                if (result.code === 200) {
                    console.log("list:", result.data);
                    ElMessage.success(result.data);
                } else {
                    ElMessage.error(`拒绝加入小组失败:`);
                }
            } catch (error) {

                ElMessage.error('拒绝加入小组失败');
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        //申请加入小组的方法
        async applyEnterGroup(data: applyEnterGroupsParams) {
            try {
                console.log("data:", data);
                const result = await reqApplyEnterGroup(data);
                console.log("result:", result);
                if (result.code === 200) {
                    console.log("list:", result.data);
                    ElMessage.success(result.data);
                } else {
                    ElMessage.error(`申请加入小组失败: ${result.data}`);
                }
            } catch (error) {

                ElMessage.error('申请加入小组失败');
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        //获取班级存在的小组的信息
        async getClassGroups(data: string) {
            try {
                console.log("data:", data);
                const result = await reqGetClassGroup(data);
                console.log("result:", result);
                if (result.code === 200) {
                    console.log("list:", result.data);
                    this.tableClassGroupData = result.data;
                } else {
                    ElMessage.error(`获取小组信息失败: ${result.msg}`);
                }
            } catch (error) {

                ElMessage.error('获取小组信息失败');
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        //发送通知的方法
        async sendNotification(data: pushNoticeParams) {
            try {
                console.log("data:", data);
                const result = await reqPushNotice(data);
                console.log("result:", result);
                if (result.code === 200) {
                    ElMessage.success(result.data)
                } else {
                    ElMessage.error(`发送信息失败: ${result.msg}`);
                }
            } catch (error) {

                ElMessage.error('发送信息失败');
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        //获取自己小组成员信息
        async getGroupList(data: getGroupListrDatePrams) {
            try {
                console.log("data:", data);
                const result = await reqGetGroupScoreList(data);
                console.log("result:", result);
                if (result.code === 200) {
                    this.tableGroupData = result.data.list;
                    this.total = result.data.total;
                } else {
                    ElMessage.error(`获取小组成员信息失败: ${result.msg}`);
                }
            } catch (error) {

                ElMessage.error('获取小组成员信息失败');
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        //在项目管理界面获取自己项目相关信息
        async studentGetGroup(data: string) {
            console.log(data);
            let result = await reqStudentGetGroup(data);
            console.log("学生获取小组信息")
            console.log(result)

            if (result.code == 200) {
                //将返回的结果存储到groupInfo中
                // 直接赋值
                console.log("接口返回的结果：", result.data);
                Object.assign(this.groupInfo, result.data);

                return 'ok';
            }
            else {
                ElMessage.error(result.msg)
                return Promise.reject(new Error(result.msg));
            }
            //存储失败 返回错误信息
        },
        //学生登录
        async studentLogin(data: studentLogin) {
            console.log(data);
            let result = await reqStudentLogin(data);

            console.log("学生登录的逻辑处理")
            console.log(result)
            //登录成功 存储token
            if (result.code == 200) {
                //pinia仓库存储token
                this.token = result.data;
                //本地持久化存储
                localStorage.setItem("TOKEN", result.data);
                return 'ok';
            }
            else {
                return Promise.reject(new Error(result.data));
            }
            //存储失败 返回错误信息
        },
        async studentRegister(data: studentRegister) {
            console.log(data);
            let result = await reqStudentRegister(data);

            console.log("学生注册的逻辑处理")
            console.log(result)
            console.log(result.code)
            //登录成功 存储token
            if (result.code == 200) {
                //注册成功 弹出一个注册成功跳转登录页面
                ElMessage.success('注册成功！');
                return 'ok';
            }
            else {
                console.log("注册失败msg", result.msg);
                //注册失败 
                ElMessage.error(result.msg);
            }
            //存储失败 返回错误信息
        },
        async studentForgetPassword(data: studentForgetPassword) {
            console.log(data);
            let result = await reqStudentForgetPassword(data);

            console.log("学生找回密码")
            console.log(result)
            //登录成功 存储token
            if (result.code == 200) {
                //找回密码成功 弹出一个找回成功跳转登录页面
                ElMessage.success('找回密码成功！');
                return 'ok';
            }
            else {
                //注册失败 
                ElMessage.error('找回密码失败 请核对后重实');

                return Promise.reject(new Error(result.data));
            }
            //存储失败 返回错误信息
        },
        async fetchStudentInfo(data: number) {
            console.log(data);
            let result = await reqStudentGetIndividualPro(data);
            //获取个人信息成功 此时更新仓库个人信息
            if (result.code == 200) {
                console.log(result);
                //找到个人信息成功 更新成仓库
                console.log("找到了个人信息 尝试更新仓库");
                this.userInfo.studentUsername = result.data.studentUsername;
                this.userInfo.studentName = result.data.studentName;
                this.userInfo.studentNumber = result.data.studentNumber;
                this.userInfo.studentEmail = result.data.studentEmail;
                this.userInfo.studentFinish = result.data.studentFinish;
                this.userInfo.studentPosition = result.data.studentPosition;
                this.userInfo.studentNotice = result.data.studentNotice;
                this.userInfo.giteeUrl = result.data.giteeUrl;
                this.userInfo.groupProName = result.data.groupProName;
                this.userInfo.groupId = result.data.groupId;
                this.userInfo.studentApplyReason = result.data.studentApplyReason;
                this.userInfo.groupNotice = result.data.groupNotice;

                return 'ok';
            }
            else {
                //注册失败 
                ElMessage.error('获取个人信息失败');

                return Promise.reject(new Error(result.msg));
            }
            //存储失败 返回错误信息
        },
        async updateInfo(updateData: studentUpdate) {
            try {
                // 假设你的API端点是 /api/students/update
                const response = await reqStudentUpdateInfo(updateData);
                if (response.code = 200) {
                    return 'ok';
                }
            } catch (error) {
                console.error("Failed to update student info", error);
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        //退出登陆
        userLogout() {
            try {
                // 调用后端登出接口（如果有的话）


                // 清除本地存储中的Token
                localStorage.removeItem("TOKEN");

                // 重置store中的token和userInfo
                this.token = '';
                this.userInfo.studentUsername = '';
                this.userInfo.studentName = '';
                this.userInfo.studentNumber = '';
                this.userInfo.studentEmail = '';
                this.userInfo.studentFinish = 0;
                this.userInfo.studentPosition = 0;
                this.userInfo.studentNotice = '';
                this.userInfo.giteeUrl = '';
                this.userInfo.groupProName = '';
                this.userInfo.groupId = -1;
                this.userInfo.groupName = '';
                this.userInfo.studentApplyReason = '';
                this.userInfo.groupNotice = ''
                ElMessage.success('退出成功');
            } catch (error) {

                ElMessage.error('退出失败，请稍后再试');
            }
        },
        //学生上传项目文件
        async uploadFile(data: StudentUploadDto) {
            console.log("uploadFile 方法被调用");
            console.log("data:", data);
            try {
                console.log("进入这了？");
                console.log("data:", data);
                const result = await reqUploadFile(data);
                if (result.code === 200) {
                    return 'ok';
                } else {
                    ElMessage.error(`文件上传失败: ${result.msg}`);
                }
            } catch (error) {
                console.error('Error uploading file:', error);
                ElMessage.error('文件上传失败');
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        //小组上传项目文件
        async uploadGroupFile(data: StudentUploadDto) {
            try {

                const result = await reqUploadGroupFile(data);
                if (result.code === 200) {
                    ElMessage.success('文件上传成功');
                } else {
                    ElMessage.error(`文件上传失败: ${result.msg}`);
                }
            } catch (error) {
                console.error('Error uploading file:', error);
                ElMessage.error('文件上传失败');
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        //获取自己小组成员信息
        async getGroupFile(data: getGroupsMemberDatePrams) {
            try {
                console.log("data:", data);
                const result = await reqGetGroupList(data);
                console.log("result:", result);
                if (result.code === 200) {
                    this.tableData = result.data.list;
                    this.total = result.data.total;
                } else {
                    ElMessage.error(`获取小组成员信息失败: ${result.msg}`);
                }
            } catch (error) {

                ElMessage.error('获取小组成员信息失败');
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        //解散小组
        async disbandGroup(data: string) {
            console.log("是否执行了这个方法");
            try {

                console.log("1111data:", data);
                const result = await reqDisbanGroup(data);
                console.log("result:", result);
                if (result.code === 200) {
                    this.tableData = [];
                    this.userInfo.groupName = '未加入小组';
                    this.userInfo.groupProName = ''
                    ElMessage.success(result.msg)
                } else {
                    ElMessage.error(`删除小组失败: ${result.msg}`);
                }
            } catch (error) {
                ElMessage.error('删除小组失败');
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        //创建小组
        async createGroup(data: CreateGroupParams) {
            console.log("是否执行了这个方法");
            try {

                console.log("1111data:", data);
                const result = await reqCreateGroup(data);
                console.log("result:", result);
                if (result.code === 200) {
                    ElMessage.success(result.msg)
                } else {
                    ElMessage.error(`创建小组失败: ${result.msg}`);
                }
            } catch (error) {
                ElMessage.error('创建小组失败');
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        //创建项目
        async createPro(data: CreateGroupParams) {
            console.log("是否执行了这个方法");
            try {

                console.log("1111data:", data);
                const result = await reqCreatePro(data);
                console.log("result:", result);
                if (result.code === 200) {
                    ElMessage.success(result.msg)
                } else {
                    ElMessage.error(`创建小组失败: ${result.msg}`);
                }
            } catch (error) {
                ElMessage.error('创建小组失败');
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        //学生进入下一个阶段
        async studentEnterNext(data: string) {
            console.log("是否执行了这个方法");
            try {

                console.log("1111data:", data);
                const result = await reqStudentEnterNext(data);
                console.log("result:", result);
                if (result.code === 200) {
                    this.userInfo.studentFinish = this.userInfo.studentFinish + 1;
                } else {
                    ElMessage.error(`进入下一个小组失败: ${result.msg}`);
                }
            } catch (error) {
                ElMessage.error('进入下一个小组失败');
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        //学生回到上一个阶段
        async studentGoBack(data: string) {
            console.log("是否执行了这个方法");
            try {

                console.log("1111data:", data);
                const result = await reqStudentGoback(data);
                console.log("result:", result);
                if (result.code === 200) {
                    this.userInfo.studentFinish = this.userInfo.studentFinish - 1;
                } else {
                    ElMessage.error(`回到上一阶段失败: ${result.msg}`);
                }
            } catch (error) {
                ElMessage.error('回到上一阶段失败');
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        //小组进入下一个阶段
        async groupEnterNext(data: string) {
            console.log("是否执行了这个方法");
            try {

                console.log("1111data:", data);
                const result = await reqGroupEnterNext(data);
                console.log("result:", result);
                if (result.code === 200) {
                    this.groupInfo.groupFinish = this.groupInfo.groupFinish + 1;
                } else {
                    ElMessage.error(`进入下一个小组失败: ${result.msg}`);
                }
            } catch (error) {
                ElMessage.error('进入下一个小组失败');
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        //小组回到上一个阶段
        async groupGoBack(data: string) {
            console.log("是否执行了这个方法");
            try {

                console.log("1111data:", data);
                const result = await reqGroupGoBack(data);
                console.log("result:", result);
                if (result.code === 200) {
                    this.groupInfo.groupFinish = this.groupInfo.groupFinish - 1;
                } else {
                    ElMessage.error(`小组回到上一个阶段失败: ${result.msg}`);
                }
            } catch (error) {
                ElMessage.error('小组回到上一个阶段失败');
                throw error; // 抛出错误以便在组件中捕获和处理
            }
        },
        //上传URL的方法
        async uploadUrl(data: uploadUrlParams) {
            try {
                const response = await reqUploadUrl(data);
                if (response.code === 200) {
                    ElMessage.success(response.data);
                }
                else {
                    ElMessage.error("上传失败");
                }
            } catch (error) {
                ElMessage.error("上传失败");
                throw error;
            }
        },
    },
    getters: {
        // 获取菜单路由
        getMenuRoutes: (state) => {
            // 如果store中的menuRoutes为空，直接返回从路由文件导入的studentRoute
            if (!state.menuRoutes || state.menuRoutes.length === 0) {
                console.log('Store menuRoutes为空，使用路由文件中的studentRoute');
                return Array.isArray(studentRoute) ? studentRoute : [studentRoute];
            }
            return state.menuRoutes;
        }
    }
})
//对外暴露获取小仓库的方法
export default useStudentStore